package com.iwdnb.gkgz.infrastructure.dao.client.impl;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.google.common.collect.Lists;
import com.iwdnb.bmnf.common.utils.HttpClientUtils;
import com.iwdnb.gkgz.common.model.dto.StockDayData;
import com.iwdnb.gkgz.infrastructure.dao.client.MairuiClient;
import com.iwdnb.gkgz.infrastructure.dao.repo.StockDayDataRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MairuiClientImpl implements MairuiClient {
    private static final List<String> TOKEN_LIST = Lists.newArrayList(
        "C7238CD0-745F-4464-AFD9-9BA420B906B1", "A13031D9-671D-44BA-882D-C039942263EC",
        "E28B8F96-2804-4B73-92A9-C4D6A81CC3E2", "B6375B7F-964E-40D8-8608-C68341C466AC",
        "5D096BED-947C-44AE-B28D-F30FE40A2CAA", "C0546A3F-E659-4290-AEE5-982DA7013D22",
        "D5DF4C3F-4E0B-467C-8E4B-51D7A4998649", "046D1F6A-9C28-4965-8298-7550BEABD11F",
        "519FFC36-3D04-49D6-A6BF-AC3D3F359CE0", "AFB13D38-511C-4AC0-A44A-0185307D9CB9",
        "6309DB28-46E6-4DC6-8F33-0267B352A101");
    //private static final List<String> TOKEN_LIST = Lists.newArrayList("519FFC36-3D04-49D6-A6BF-AC3D3F359CE0" );
    private static Integer TOKEN_COUNT = 0;
    private static final String ZS_URL = "http://api.mairui.club/zs/sh/";

    private static final String ZS_KLINE_URL = "https://api.mairui.club/zs/hfsjy/%s/dn/";
    /**
     * 行业列表
     */
    private static final String INDUSTRY_URL = "http://api.mairui.club/hszg/list/";
    /**
     * 行业下的股票链接
     */
    private static final String INDUSTRY_STOCK_URL = "http://api.mairui.club/hszg/gg/%s/";

    @Autowired
    private StockDayDataRepository stockDayDataRepository;

    @Override
    public void initZsList() {
        String token = getToken();
        if (StringUtils.isBlank(token)) {
            log.error("token已耗尽,请明天再试");
            return;
        }
        String body = HttpClientUtils.get(ZS_URL + token);
        if (!body.startsWith("[")) {
            initZsList();
            return;
        }
        JSONArray jsonArray = JSON.parseArray(body);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            String code = object.getString("dm");
            String name = object.getString("mc");
            System.out.println(code.toUpperCase() + "(\"" + code + "\",\"" + name + "\"),");
        }
    }

    @Override
    public void initZsStockDayDataList(String zsCode) {
        String token = getToken();
        if (StringUtils.isBlank(token)) {
            log.error("token已耗尽,请明天再试");
            return;
        }
        String zsKlineUrl = String.format(ZS_KLINE_URL + token, zsCode);
        String body = HttpClientUtils.get(zsKlineUrl);
        if (!body.startsWith("[")) {
            initZsStockDayDataList(zsCode);
            return;
        }
        JSONArray jsonArray = JSON.parseArray(body);
        List<StockDayData> stockDayDataList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            StockDayData data = new StockDayData();
            data.setDate(object.getString("d"));
            data.setOpenPrice(object.getBigDecimal("o"));
            data.setClosePrice(object.getBigDecimal("c"));
            data.setMinPrice(object.getBigDecimal("l"));
            data.setMaxPrice(object.getBigDecimal("h"));
            data.setTradeNum(object.getInteger("v"));
            stockDayDataList.add(data);
        }
        log.info("{}指数k线数据:{}", zsCode, JSON.toJSONString(stockDayDataList));
        stockDayDataRepository.saveAll(zsCode, stockDayDataList);
    }

    @Override
    public void initIndustryList() {
        String token = getToken();
        if (StringUtils.isBlank(token)) {
            log.error("token已耗尽,请明天再试");
            return;
        }
        String body = HttpClientUtils.get(INDUSTRY_URL + token);
        if (!body.startsWith("[")) {
            initIndustryList();
            return;
        }
        JSONArray jsonArray = JSON.parseArray(body);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            if (object.getString("pname").equals("A股-申万行业")) {
                String code = object.getString("code");
                String name = object.getString("name");
                name = name.replaceAll("A股-申万行业-", "");
                System.out.println(code + "(\"" + code + "\", \"" + name + "\"),");
            }
        }
        System.out.println("===================二级行业=====================================");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            if (object.getString("pname").equals("A股-申万二级")) {
                String code = object.getString("code");
                String name = object.getString("name");
                name = name.replaceAll("A股-申万二级-", "");

                System.out.println(code + "(\"" + code + "\", \"" + name + "\"),");
            }
        }
        System.out.println("====================热门概念====================================");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            if (object.getString("pname").equals("A股-热门概念")) {
                String code = object.getString("code");
                String name = object.getString("name");
                name = name.replaceAll("A股-热门概念-", "");

                System.out.println(code + "(\"" + code + "\", \"" + name + "\"),");
            }
        }
    }

    @Override
    public List<String> getStockListByIndustry(String industryCode) {
        String token = getToken();
        if (StringUtils.isBlank(token)) {
            log.error("token已耗尽,请明天再试");
            return null;
        }
        String url = String.format(INDUSTRY_STOCK_URL + token, industryCode);
        String body = HttpClientUtils.get(url);
        if (StringUtils.isBlank(body)) {
            return null;
        }
        if (!body.startsWith("[")) {
            return getStockListByIndustry(industryCode);
        }
        List<String> list = new ArrayList<>();
        JSONArray jsonArray = JSON.parseArray(body);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            String code = object.getString("dm");
            String jys = object.getString("jys");
            list.add(jys + code);
        }
        return list;
    }

    @Override
    public void initStockIndustry(List<String> codeList) {

    }

    private static String getToken() {
        TOKEN_COUNT++;
        int index = TOKEN_COUNT / 50;
        if (index >= TOKEN_LIST.size() - 1) {
            return null;
        }
        return TOKEN_LIST.get(index);
    }

    public static void main(String[] args) {
        MairuiClient mairuiClient = new MairuiClientImpl();
        //mairuiClient.initZsList();
        mairuiClient.initIndustryList();
        //mairuiClient.getStockListByIndustry("sw_mt");
    }
}
